package com.controller;

import com.entity.VehicleInsurance;
import com.service.VehicleInsuranceService;
import com.dto.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/api/vehicle/insurance")
public class VehicleInsuranceController {

    @Autowired
    private VehicleInsuranceService vehicleInsuranceService;

    @PostMapping
    public VehicleInsurance create(@RequestBody VehicleInsurance vehicleInsurance) {
        return vehicleInsuranceService.save(vehicleInsurance);
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable(value = "id") Integer id) {
        vehicleInsuranceService.deleteById(id);
    }

    @PutMapping("/{id}")
    public VehicleInsurance update(@PathVariable(value = "id") Integer id, @RequestBody VehicleInsurance vehicleInsurance) {
        vehicleInsurance.setId(id);
        return vehicleInsuranceService.save(vehicleInsurance);
    }

    @GetMapping("/{id}")
    public VehicleInsurance detail(@PathVariable(value = "id") Integer id) {
        return vehicleInsuranceService.findById(id).orElse(null);
    }

    @GetMapping("/page")
    public Page<VehicleInsurance> page(@RequestParam(defaultValue = "1") int pageNum,
                                               @RequestParam(defaultValue = "10") int pageSize,
                                               @RequestParam(required = false) String plateNumber) {
        Page<VehicleInsurance> page;
        if (plateNumber != null && !plateNumber.isEmpty()) {
            page = vehicleInsuranceService.findByPlateNumberContaining(plateNumber, pageNum, pageSize);
        } else {
            page = vehicleInsuranceService.findAll(pageNum, pageSize);
        }
        return page;
    }
}